import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {MessageService} from '@/utils/message'
import {authService} from '@/services/authService'
import {getCurrentDateTime} from '@/utils/date'
import type {LoginRequest, User, UserStatus, UserType} from '@/types/business/auth'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const loginLoading = ref(false)

  // 计算属性 - 直接从localStorage读取token，避免双重同步
  const accessToken = computed(() => localStorage.getItem('accessToken'))
  const refreshToken = computed(() => localStorage.getItem('refreshToken'))
  const isAuthenticated = computed(() => !!accessToken.value && !!user.value)
  const currentUser = computed(() => user.value)
  const userRole = computed(() => user.value?.userType || null)
  const isAdmin = computed(() =>
    userRole.value === 'ADMIN' || userRole.value === 'SUPER_ADMIN'
  )
  const isSuperAdmin = computed(() => userRole.value === 'SUPER_ADMIN')
  const canManageUsers = computed(() => isAdmin.value)

  // 权限检查
  const hasPermission = (requiredRole: UserType) => {
    if (!user.value) return false

    const roleHierarchy = {
      'SUPER_ADMIN': 4,
      'ADMIN': 3,
      'DEVELOPER': 2,
      'VIEWER': 1
    }

    const userLevel = roleHierarchy[user.value.userType] || 0
    const requiredLevel = roleHierarchy[requiredRole] || 0

    return userLevel >= requiredLevel
  }

  // 初始化 - 从localStorage恢复用户信息
  const initAuth = () => {
    const storedUser = localStorage.getItem('userInfo')
    const storedToken = localStorage.getItem('accessToken')

    if (storedToken && storedUser) {
      user.value = JSON.parse(storedUser)
      console.log('[Auth] 认证状态已恢复')
    } else {
      console.warn('[Auth] 未找到有效的认证信息')
    }
  }

  // 登录
  const login = async (credentials: LoginRequest): Promise<boolean> => {
    try {
      loginLoading.value = true
      const response = await authService.login(credentials)
      const { accessToken: token, refreshToken: refresh, userInfo } = response.data!

      // 只持久化存储到localStorage，token通过computed读取
      localStorage.setItem('accessToken', token)
      localStorage.setItem('refreshToken', refresh)

      user.value = {
        ...userInfo,
        userType: userInfo.userType as UserType,
        status: userInfo.status as UserStatus,
        createTime: getCurrentDateTime(),
        updateTime: getCurrentDateTime()
      }
      localStorage.setItem('userInfo', JSON.stringify(user.value))

      MessageService.success('登录成功')
      return true
    } catch (error: any) {
      console.error('登录失败:', error)
      const message = error.response?.data?.message || '登录失败'
      MessageService.error(message)
      return false
    } finally {
      loginLoading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      await authService.logout()
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 只清除localStorage存储，token会自动通过computed返回null
      user.value = null
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
      MessageService.success('已登出')
    }
  }

  // 刷新令牌
  const refreshAccessToken = async (): Promise<boolean> => {
    try {
      const currentRefreshToken = refreshToken.value
      if (!currentRefreshToken) {
        throw new Error('No refresh token')
      }

      const response = await authService.refreshToken(currentRefreshToken)
      const { accessToken: token, refreshToken: refresh, userInfo } = response.data!

      // 只更新localStorage存储，token会自动通过computed读取
      localStorage.setItem('accessToken', token)
      localStorage.setItem('refreshToken', refresh)

      user.value = {
        ...userInfo,
        userType: userInfo.userType as UserType,
        status: userInfo.status as UserStatus,
        createTime: user.value?.createTime || getCurrentDateTime(),
        updateTime: getCurrentDateTime()
      }
      localStorage.setItem('userInfo', JSON.stringify(user.value))

      return true
    } catch (error) {
      console.error('令牌刷新失败:', error)
      // 刷新失败，自动登出
      await logout()
      return false
    }
  }

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    try {
      const response = await authService.getCurrentUser()
      user.value = {
        ...response.data!,
        userType: response.data!.userType as UserType,
        status: response.data!.status as UserStatus
      }
      localStorage.setItem('userInfo', JSON.stringify(user.value))
    } catch (error) {
      console.error('获取用户信息失败:', error)
      await logout()
    }
  }

  return {
    // 状态
    user,
    accessToken,
    refreshToken,
    loginLoading,

    // 计算属性
    isAuthenticated,
    currentUser,
    userRole,
    isAdmin,
    isSuperAdmin,
    canManageUsers,

    // 方法
    hasPermission,
    initAuth,
    login,
    logout,
    refreshAccessToken,
    fetchCurrentUser
  }
})